/**
 * 全局应用状态管理
 * 使用React Context API实现跨页面状态共享
 */
import React, { createContext, useContext, useState, ReactNode } from 'react';

import { CarProgressResponseItem } from '../types/myself';
import { UserInfoType, CoachCommentItem } from '../types/user';
import { CityBaseItem, RegionNode, CityBaseData, LicenseItem, Position } from '../types/cityBase';


/**
 * 全局应用状态类型定义
 * 包含需要跨页面持久化的用户选择状态
 */
interface AppState {
    carSubjectProcess: CarProgressResponseItem;
    userInfo: UserInfoType | null;
    myCoachInfo: UserInfoType | null;
    carLicenseList: {[key: string]: LicenseItem};
    cityDrivingBaseList: CityBaseItem[];
    selectedRegionPath: string[];
    selectedDistrict: string;
    selectedNode: RegionNode | null;
    selectedParentNode: RegionNode | null;
    selectedCityBaseData: CityBaseData | null;
    userLocation: Position | null;
    commentDetail: CoachCommentItem | null;
}

/**
 * 全局Context类型定义
 * 包含状态和修改状态的方法
 */
interface AppContextType extends AppState {
    setUserInfo: (userInfo: UserInfoType | null) => void;
    setSelectedRegionPath: (path: string[]) => void;
    setSelectedDistrict: (district: string) => void;
    setSelectedNode: (node: RegionNode | null) => void;
    setSelectedParentNode: (node: RegionNode | null) => void;
    setCityDrivingBaseList: (list: CityBaseItem[]) => void;
    setSelectedCityBaseData: (data: CityBaseData) => void;
    setSelectedCityBaseDataDefault: () => void;
    setCarLicenseList: (list: {[key: string]: LicenseItem}) => void;
    setUserLocation: (data: Position | null) => void;
    setCommentDetail: (data: CoachCommentItem | null) => void;
    setMyCoachInfo: (data: UserInfoType | null) => void;
    setCarSubjectProcess: (status: CarProgressResponseItem) => void;
    setCarSubjectStepProcessStatus: (stepId: number, status: number) => void;
}

// 初始状态定义
const initialState: AppState = {
    userInfo: null,
    myCoachInfo: null,
    carLicenseList: {},
    cityDrivingBaseList: [],
    selectedRegionPath: [],
    selectedDistrict: '',
    selectedNode: null,
    selectedParentNode: null,
    selectedCityBaseData: null,
    userLocation: null,
    commentDetail: null,
    carSubjectProcess: {},
};

// 创建Context
const AppContext = createContext<AppContextType | undefined>(undefined);

/**
 * AppContext Provider组件
 * @param children 子组件
 * @returns Provider组件
 */
export const AppProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [userInfo, setUserInfo] = useState<UserInfoType | null>(initialState.userInfo);
    const [userLocation, setUserLocation] = useState<Position | null>(initialState.userLocation);
    const [myCoachInfo, setMyCoachInfo] = useState<UserInfoType | null>(initialState.myCoachInfo);
    const [selectedNode, setSelectedNode] = useState<RegionNode | null>(initialState.selectedNode);
    const [selectedDistrict, setSelectedDistrict] = useState<string>(initialState.selectedDistrict);
    const [commentDetail, setCommentDetail] = useState<CoachCommentItem | null>(initialState.commentDetail);
    const [selectedRegionPath, setSelectedRegionPath] = useState<string[]>(initialState.selectedRegionPath);
    const [carLicenseList, setCarLicenseList] = useState<{[key: string]: LicenseItem}>(initialState.carLicenseList);
    const [cityDrivingBaseList, setCityDrivingBaseList] = useState<CityBaseItem[]>(initialState.cityDrivingBaseList);
    const [selectedParentNode, setSelectedParentNode] = useState<RegionNode | null>(initialState.selectedParentNode);
    const [carSubjectProcess, setCarSubjectProcess] = useState<CarProgressResponseItem>(initialState.carSubjectProcess);
    const [selectedCityBaseData, setSelectedCityBaseData] = useState<CityBaseData | null>(initialState.selectedCityBaseData);

    /**
     * 设置默认选中的城市基地数据
     */
    const setSelectedCityBaseDataDefault = () => {
        setSelectedCityBaseData(null);
    };

    const setCarSubjectStepProcessStatus = (stepId: number, status: number) => {
        console.log('setCarSubjectStepProcessStatus', stepId, status);
        const updatedProcess = { ...carSubjectProcess };
        let stepFound = false;
        Object.keys(updatedProcess).forEach(key => {
            const carStep = updatedProcess[key];
            if (Array.isArray(carStep)) {
                const targetStep = carStep.find(step => step.id === stepId);
                if (targetStep) {
                    console.log('找到匹配的步骤:', targetStep);
                    targetStep.status = status;
                    stepFound = true;
                }
            } else if (carStep && typeof carStep === 'object') {
                // 单个对象的情况
                if (carStep.id === stepId) {
                    carStep.status = status;
                    console.log('更新匹配的步骤:', carStep);
                    stepFound = true;
                }
            }
        });

        if (stepFound) {
            console.log('更新后的carSubjectProcess:', updatedProcess);
            setCarSubjectProcess(updatedProcess);
        } else {
            console.warn(`未找到ID为${stepId}的步骤`);
        }
    };

    // 提供的Context值
    const contextValue: AppContextType = {
        userInfo,
        myCoachInfo,
        carLicenseList,
        cityDrivingBaseList,
        selectedRegionPath,
        selectedDistrict,
        selectedNode,
        selectedParentNode,
        selectedCityBaseData,
        userLocation,
        commentDetail,
        carSubjectProcess,
        setUserInfo,
        setSelectedRegionPath,
        setSelectedDistrict,
        setSelectedNode,
        setSelectedParentNode,
        setCityDrivingBaseList,
        setSelectedCityBaseData,
        setSelectedCityBaseDataDefault,
        setCarLicenseList,
        setUserLocation,
        setCommentDetail,
        setMyCoachInfo,
        setCarSubjectProcess,
        setCarSubjectStepProcessStatus
    };

    return (
        <AppContext.Provider value={contextValue}>
            {children}
        </AppContext.Provider>
    );
};

/**
 * 使用AppContext的自定义Hook
 * @returns AppContextType
 */
export const useAppContext = (): AppContextType => {
    const context = useContext(AppContext);
    if (context === undefined) {
        throw new Error('useAppContext must be used within an AppProvider');
    }
    return context;
};